<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <!-- navigator 包含有关浏览器的信息-->

    <div id="demo"></div>



    <script src="./js/jquery-3.2.1.js"></script>
    <script>
        var model = (function () {
            // 方法一：
            function onlineOne() {
                if (window.navigator.onLine) {
                    alert('网络连接中');
                    alert(window.navigator.connection.type); //监测网络类型，目前只能用于移动端
                } else {
                    alert('网络断开中');
                }
            }
            //方法二：
            function onlineTwo() {
                var userAgent = navigator.userAgent;
                window.addEventListener('online', function () {
                    $('#demo').text('网络已连接').fadeIn(500).delay(1000).fadeOut();
                });
                window.addEventListener('offline', function () {
                    $('#demo').text('网络已断开').fadeIn(500).delay(1000).fadeOut();
                });
                if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
                    window.attachEvent('online', function () {
                        $('#demo').text('网络已连接').fadeIn(500).delay(1000).fadeOut();
                    });
                    window.attachEvent('offline', function () {
                        $('#demo').text('网络已断开').fadeIn(500).delay(1000).fadeOut();
                    });
                }
            }


            return {
                onlineOne: onlineOne,
                onlineTwo: onlineTwo
            }
        })()

        $(function () {
            model.onlineOne();
        })
    </script>
</body>

</html>